package me.liuyu2783.dubbo.sample.http;

import com.alibaba.fastjson.JSON;
import me.liuyu2783.dubbo.sample.dubbo.Invocation;
import me.liuyu2783.dubbo.sample.dubbo.LocalRegister;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * me.liuyu2783.dubbo.sample.tomcat
 *
 * @author liuyu2783
 * @date 2020-3-3
 */
public class HttpServerHandler {

    void handler(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("---------------");
        Invocation invocation = JSON.parseObject(req.getInputStream(), Invocation.class);

        try {
            Class clazz = LocalRegister.getByName(invocation.getInterfaceName());
            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamType());
            Object result = method.invoke(clazz.newInstance(), invocation.getParams());

            PrintWriter out = resp.getWriter();
            out.write(result.toString());
            out.flush();
            out.close();

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
